const vscode = require('vscode');
const axios = require('axios');
const OpenAI = require('openai');
const inlineCompletionProvider = require('./src/inlineCompletion.js');
const fs = require('fs');
const path = require('path');
const registerExplainCodeCommand = require('./src/explainCodeCommand.js');
const registerAddCommentCommand = require('./src/addCommentCommand.js');
const { registerAddToChatCommand } = require('./src/addToChatCommand');
const registerProblemCommands = require('./src/problemCommands');
const ChatViewProvider = require('./src/chatViewProvider.js');
const AgentTask = require('./src/agent/agentTask');
const FileCreator = require('./src/agent/fileCreator');
const { searchWorkspaceFiles, parseMentions } = require('./src/context/ContextMentions');
const { McpService } = require('./src/services/mcp/McpService');
const { McpCommandManager } = require('./src/services/mcp/McpCommandManager.js');
const { McpViewProvider } = require('./src/webview/McpViewProvider.js');
const { initializeMcp } = require('./src/mcpExtension');

// 存储全局的MCP服务实例
let mcpService = null;
let qwenChatView = null;

function activate(context) {
    try {
        // 立即创建并预热WebView（但不初始化代理，让ChatViewProvider自己处理）
        const chatViewProvider = new ChatViewProvider(context);
        chatViewProvider.warmup(); // 预热HTML内容
        
        // 注册聊天视图提供程序
        context.subscriptions.push(
            qwenChatView = chatViewProvider,
            vscode.window.registerWebviewViewProvider('qwenChatView', chatViewProvider, {
                webviewOptions: { retainContextWhenHidden: true }
            })
        );
        
        // 在插件激活后立即尝试显示一次WebView，这有助于预热并保持状态
        setTimeout(() => {
            try {
                // 尝试激活聊天视图
                vscode.commands.executeCommand('qwenChatView.focus').then(
                    () => console.log('聊天视图已激活'),
                    err => console.error('激活聊天视图失败:', err)
                );
            } catch (error) {
                console.error('激活聊天视图时出错:', error);
            }
        }, 500);

        const inlineProvider = inlineCompletionProvider();
        context.subscriptions.push(
            vscode.languages.registerInlineCompletionItemProvider(
                { pattern: "**/*" },
                inlineProvider
            )
        );

        // 注册代码补全命令
        let codeCompletionCommand = vscode.commands.registerCommand('gptdemo.codeCompletion', () => {
            // 触发内联补全
            vscode.commands.executeCommand('editor.action.inlineCompletion.trigger');
        });

        context.subscriptions.push(codeCompletionCommand);

        // 更新解释代码命令
        registerExplainCodeCommand(context, chatViewProvider);

        // 注册添加注释命令
        registerAddCommentCommand(context);
        
        // 注册添加到对话框命令
        registerAddToChatCommand(context, chatViewProvider);
        
        // 注册新对话命令
        let newChatCommand = vscode.commands.registerCommand('gptdemo.newChat', () => {
            // 发送clearContext消息到webview
            if (chatViewProvider && chatViewProvider._view) {
                chatViewProvider._view.webview.postMessage({
                    command: 'clearContext'
                });
                
                // 同时清除AI服务和代理任务的历史
                try {
                    if (typeof chatViewProvider.agentTask?.clearConversationHistory === 'function') {
                        chatViewProvider.agentTask.clearConversationHistory();
                    }
                    
                    const { resetConversationHistory } = require('./utils/utils.js');
                    if (typeof resetConversationHistory === 'function') {
                        resetConversationHistory();
                    }
                } catch (error) {
                    console.error('清除历史记录错误:', error);
                }
                
                vscode.window.showInformationMessage('已开始新对话');
            } else {
                vscode.window.showInformationMessage('请先打开聊天视图');
            }
        });
        
        context.subscriptions.push(newChatCommand);
        
        // 注册创建文件命令
        let createFileCommand = vscode.commands.registerCommand('gptdemo.createFile', async () => {
            // 使用chatViewProvider中的fileCreator实例
            if (!chatViewProvider.fileCreator) {
                vscode.window.showErrorMessage('文件创建器未初始化，请确保工作区已打开');
                return;
            }
            
            // 获取文件名
            const fileName = await vscode.window.showInputBox({
                prompt: '请输入要创建的文件名',
                placeHolder: '例如: component.js'
            });
            
            if (!fileName) return;
            
            try {
                // 检查参数数量并正确调用
                const fileInfo = await chatViewProvider.fileCreator.createFile(
                    fileName,
                    '', // 默认空内容
                    null // 默认目标目录
                );
                if (fileInfo.success) {
                    vscode.window.showInformationMessage(`文件创建成功: ${fileInfo.relativePath}`);
                } else {
                    vscode.window.showErrorMessage(`文件创建失败: ${fileInfo.error}`);
                }
            } catch (error) {
                vscode.window.showErrorMessage(`文件创建出错: ${error.message}`);
            }
        });
        
        context.subscriptions.push(createFileCommand);

        // 注册问题视图命令
        registerProblemCommands(context, chatViewProvider);

        // 注册文件变更通知命令
        context.subscriptions.push(
            vscode.commands.registerCommand('xinye.notifyFileChange', ({filePath, operation, changeInfo}) => {
                // 通知WebView
                chatViewProvider.notifyFileChange(filePath, operation, changeInfo);
            }),
            vscode.commands.registerCommand('xinye.notifyFileChangeConfirmed', ({filePath, operation}) => {
                // 通知WebView
                chatViewProvider.notifyFileChangeConfirmed(filePath, operation);
            }),
            vscode.commands.registerCommand('xinye.notifyFileChangeRejected', ({filePath}) => {
                // 通知WebView
                chatViewProvider.notifyFileChangeRejected(filePath);
            })
        );

        // 注册代码操作提供程序
        context.subscriptions.push(
            vscode.languages.registerCodeActionsProvider(
                '*',
                {
                    provideCodeActions(document, range, context) {
                        // 扩展选择范围以包含周围3行
                        const expandedRange = new vscode.Range(
                            Math.max(0, range.start.line - 3),
                            0,
                            Math.min(document.lineCount - 1, range.end.line + 3),
                            document.lineAt(Math.min(document.lineCount - 1, range.end.line + 3)).text.length
                        );

                        // 只在有诊断信息（问题）时提供操作
                        if (context.diagnostics.length > 0) {
                            const actions = [];
                            
                            // 获取问题所在的代码上下文
                            const problemCode = document.getText(expandedRange);
                            const diagnostic = context.diagnostics[0];
                            
                            // 添加"使用xinye解释"操作
                            const explainAction = new vscode.CodeAction(
                                '使用xinye解释',
                                vscode.CodeActionKind.QuickFix
                            );
                            explainAction.command = {
                                command: 'gptdemo.explainProblem',
                                title: '使用xinye解释',
                                arguments: [
                                    {
                                        message: diagnostic.message,
                                        file: document.fileName,
                                        line: range.start.line + 1,
                                        code: problemCode,
                                        severity: diagnostic.severity,
                                        source: diagnostic.source
                                    }
                                ]
                            };
                            actions.push(explainAction);

                            // 添加"使用xinye修复"操作
                            const fixAction = new vscode.CodeAction(
                                '使用xinye修复',
                                vscode.CodeActionKind.QuickFix
                            );
                            fixAction.command = {
                                command: 'gptdemo.fixProblem',
                                title: '使用xinye修复',
                                arguments: [
                                    {
                                        message: diagnostic.message,
                                        file: document.fileName,
                                        line: range.start.line + 1,
                                        code: problemCode,
                                        severity: diagnostic.severity,
                                        source: diagnostic.source
                                    }
                                ]
                            };
                            actions.push(fixAction);

                            return actions;
                        }

                        return [];
                    }
                }
            )
        );

        // 添加MCP视图命令
        context.subscriptions.push(
            vscode.commands.registerCommand('mcp.openView', async () => {
                await vscode.commands.executeCommand('workbench.view.extension.mcpConfigView');
            })
        );
        context.subscriptions.push(
            vscode.commands.registerCommand("gptdemo.mcpSettingsButtonClicked", () => {
                // 切换到MCP管理视图
                if (chatViewProvider && chatViewProvider._view) {
                    chatViewProvider.showMcpManager();
                }
            })
        );

        // 添加返回聊天视图的命令
        context.subscriptions.push(
            vscode.commands.registerCommand("gptdemo.backToChatView", () => {
                // 切换回聊天视图
                if (chatViewProvider && chatViewProvider._view) {
                    chatViewProvider.showChatView();
                }
            })
        );

        // 初始化MCP功能
        initializeMcp(context, { chatViewProvider })
            .then(service => {
                // 存储全局MCP服务实例
                mcpService = service;
                
                // 添加到全局对象，方便其他模块访问
                global.getMcpService = () => mcpService;
                
                // 将MCP服务设置到聊天视图提供者
                if (chatViewProvider) {
                    chatViewProvider.setMcpService(service);
                }
                
                console.log('MCP服务初始化成功');
            })
            .catch(error => {
                console.error('MCP服务初始化失败:', error);
            });

        // 提供接口供其他扩展访问
        return {
            getMcpService: () => mcpService
        };
    } catch (err) {
        vscode.window.showErrorMessage(`扩展激活失败: ${err.message}`);
        console.error('扩展激活失败:', err);
    }
}

function deactivate() {
    // 清理资源
    if (mcpService) {
        console.log('清理MCP资源...');
        // MCP服务目前不需要特别的清理逻辑
    }
}

module.exports = {
    activate,
    deactivate
};
